package com.syy.chart.service.impl;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.syy.chart.domain.WfForm;
import com.syy.chart.mapper.OperateTableMapper;
import com.syy.chart.mapper.WfFormMapper;
import com.syy.chart.service.IWfFormService;
import com.syy.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
/**
 * 动态表单实现层业务类
 */
@Service
public class WfFormServiceImpl implements IWfFormService {

    private static final Logger log = LoggerFactory.getLogger(WfFormServiceImpl.class);

    @Resource
    private WfFormMapper wfFormMapper;
    @Resource
    private OperateTableMapper operateTableMapper;

    @Override
    public int addWfForm(WfForm wfForm) {
        //1:添加表数据
        int res = wfFormMapper.addWfForm(wfForm);
        //2：创建表
        operateTableMapper.createTable(wfForm.getFormTableName());
        return res;
    }

    @Override
    public List<WfForm> selectWfFormList(WfForm wfForm) {
        return wfFormMapper.selectWfFormList(wfForm);
    }

    @Override
    public int deleteWfFormByIds(String[] ids) {
        //1:根据ids查询所有要删除的表的数据
        List<WfForm> wfFormList = wfFormMapper.queryWfFormByIds(ids);
        System.out.println(wfFormList);
        //2：删除wf_form表中的数据
        int delRes = wfFormMapper.deleteWfFormByIds(ids);
        //3：删除数据库中的表
        for (WfForm wfForm : wfFormList) {
            System.out.println(wfForm);
            operateTableMapper.dropTable(wfForm.getFormTableName());
        }
        return delRes;
    }

    /**
     * 更新表单
     * @param wfForm
     * @return
     */
    @Override
    @Transactional   // 增加事务处理
    public int updateForm(WfForm wfForm) {
        try {
            //1：更新wf_form
            int updateRes = wfFormMapper.updateForm(wfForm);
            //2：根据fields 去创建表字段
            if(StringUtils.isNotEmpty(wfForm.getAllFields()) && wfForm.getAllFields().length()>2){
                String columnSql = getTableColumnSql(wfForm.getFormTableName(),wfForm.getAllFields());
                if(StringUtils.isNotEmpty(columnSql)){ // 筛选掉重复的列'
                    System.out.println("columnSql = " + columnSql);
                    String tableName = wfForm.getFormTableName();
                    System.out.println("tableName = " + tableName);
                    operateTableMapper.updateFormTable(tableName,columnSql);
                }
            }
            return updateRes;
        }catch(Exception e){
            return 0;
        }
    }
    /**
     * 获取表格列sql语句   DDL
     * @param tableName
     * @param allFields
     * @return
     */
    public String getTableColumnSql(String tableName,String allFields){
        //1:根据表名 查看已经存在的字段有哪些
        System.out.println("tableName = " + tableName);
        System.out.println("allFields = " + allFields);
        List existFieldsList = operateTableMapper.getTableColumn(tableName);
        System.out.println("existFieldsList = " + existFieldsList);
        JSONArray fieldsArray = JSONUtil.parseArray(allFields);
        System.out.println(fieldsArray);
        int fieldSize = fieldsArray.size();
        String columnSql = "";
        for (int i = 0; i < fieldsArray.size(); i++) {
            JSONObject fieldObj = (JSONObject)fieldsArray.get(i);
            String field = (String)fieldObj.get("field");
            // 2：不存在的字段才去加，存在的就不加了
            Boolean flag = false;
            for (int j = 0; j < existFieldsList.size(); j++) {
                HashMap<String,String> existFieldHash = (HashMap<String,String>)existFieldsList.get(j);
                String existField = existFieldHash.get("name");
                if(field.equals(existField)){
                    flag = true;
                }
            }
            if(flag){
                fieldSize--;
                continue;
            }
            // 3：构造DDL语句
            String comment = (String)fieldObj.get("title");
            String type = (String)fieldObj.get("type");
            String col = "";
            JSONObject props = (JSONObject)fieldObj.get("props");
            if("input".equals(type)){
                if(props!=null && (String)props.get("type")!=null){
                    String propType = (String)props.get("type");
                    if("textarea".equals(propType)){
                        col=" longtext "+"CHARACTER SET utf8 COLLATE utf8_general_ci ";
                    }else{
                        col=" varchar(255) "+"CHARACTER SET utf8 COLLATE utf8_general_ci ";
                    }
                }else{
                    col=" varchar(255) "+"CHARACTER SET utf8 COLLATE utf8_general_ci ";
                }
            }else if("datePicker".equals(type)){
                col=" date ";
                if(props!=null && (String)props.get("type")!=null){
                    String propType = (String)props.get("type");
                    if("datetime".equals(propType)){
                        col=" datetime ";
                    }
                }
            }else if("timePicker".equals(type)){
                col=" datetime ";
            }else if("upload".equals(type)){
                col=" varchar(255) "+"CHARACTER SET utf8 COLLATE utf8_general_ci ";
            }else if("inputNumber".equals(type)){
                col= " int(20) ";
            }else if("radio".equals(type) || "switch".equals(type)){
                col= " int(10) ";
            }else if ("fc-editor".equals(type)){ // 富文本编辑器
                col= " longtext CHARACTER SET utf8 COLLATE utf8_general_ci ";
            }else{
                col= " varchar(255) "+"CHARACTER SET utf8 COLLATE utf8_general_ci ";
            }
            if(!StringUtils.isNotEmpty(comment)){
                comment = "字段名称";
            }
            String sql = field + col +"NULL DEFAULT NULL COMMENT \'" + comment+"\'";
            if(i < fieldSize - 1){ // 不是最后一个的时候才加逗号
                sql = sql + ",";
            }
            columnSql = columnSql + sql;
        }
        return columnSql;
    }
    /**
     * 根据表单id，获取所有字段
     * @param formId
     * @return
     */
    @Override
    public WfForm getAllFields(String formId) {
        WfForm wfForm =wfFormMapper.getAllFields(formId);
        return wfForm;
    }
}
